package com.googlecode.bushel.obr.filter;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.bushel.obr.xml.RequirementFilter;

public abstract class MultiOperatorFilter extends RequirementFilter {

    private List<RequirementFilter> subFilters = new ArrayList<RequirementFilter>();

    public MultiOperatorFilter() {
        // default constructor
    }

    public MultiOperatorFilter(RequirementFilter... filters) {
        for (RequirementFilter filter : filters) {
            add(filter);
        }
    }

    abstract protected char operator();

    @Override
    public void append(StringBuilder builder) {
        builder.append('(');
        builder.append(operator());
        for (RequirementFilter filter : subFilters) {
            filter.append(builder);
        }
        builder.append(')');
    }

    public void add(RequirementFilter subFilter2) {
        subFilters.add(subFilter2);
    }

    public List<RequirementFilter> getSubFilters() {
        return subFilters;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        for (RequirementFilter subFilter : subFilters) {
            result = prime * result + ((subFilter == null) ? 0 : subFilter.hashCode());
        }
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof MultiOperatorFilter)) {
            return false;
        }
        MultiOperatorFilter other = (MultiOperatorFilter) obj;
        if (subFilters == null) {
            if (other.subFilters != null) {
                return false;
            }
        } else if (other.subFilters == null) {
            return false;
        } else if (subFilters.size() != other.subFilters.size()) {
            return false;
        } else if (!subFilters.containsAll(other.subFilters)) {
            return false;
        }
        return true;
    }
}
